package com.bb.blog.code.mq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RabbitMqExample2 {
    private static final String TASK_QUEUE_NAME = "task_queue";

    static class Prod{
        public static void main(String[] args) throws IOException, TimeoutException {
            ConnectionFactory connectionFactory = new ConnectionFactory();
            connectionFactory.setHost("localhost");
            Connection connection = connectionFactory.newConnection();
            Channel channel = connection.createChannel();
            channel.queueDeclare(TASK_QUEUE_NAME,true,false,false,null);
            String message = "taskqueue";
            int i = 1000000;
            for (; ; i++) {
                String msg = message+i;
                channel.basicPublish("",TASK_QUEUE_NAME, MessageProperties.TEXT_PLAIN,msg.getBytes(StandardCharsets.UTF_8));
                System.out.println("send " + msg);

            }


        }
    }


    static class Consumer{
        public static void main(String[] args) throws IOException, TimeoutException {
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("localhost");
            final Connection connection = factory.newConnection();
            final Channel channel = connection.createChannel();

            channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
            System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

            //channel.basicQos(1);

            DeliverCallback deliverCallback = (consumerTag, delivery) -> {
                String message = new String(delivery.getBody(), "UTF-8");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                }
                System.out.println(" [x] Received '" + message + "'");
            };
            channel.basicQos(10);
            channel.basicConsume(TASK_QUEUE_NAME, false, deliverCallback, consumerTag -> { });

        }
    }
}
